<?php
require_once OUTER_PATH."auth/User.php";
class innerUser extends SDO_Controller
{
	public function __construct()
	{
		parent::__construct();
		header("Content-type:text/html;charset=utf-8");
		$this->load->model("Events");
		$this->load->helper("ip");
		if (!ip_helper::is_company())
			die("非公司网络，不允许登录！！！");
		$this->load->helper("user");
		if (!isset($_SESSION['username']))
			redirect('/welcome');
	}

	public function index()
	{
		redirect('/innerUser/AgentRequestList');
	}

	public function NewRequestByAgent()
	{
		$this->load->model('options');
		$this->load->model('groups');
		$this->load->model('workers');

	    if (!isset($_GET['eventId']) || !$_GET['eventId']) {
	    	$eventId = $this->Events->createEvent('', '', $_SESSION['username'], 0, 0, array(
	    	'event_status'=>0,
	    	'event_isstaff'=>Events::USER_STAFF_INNER
	    	));
	    } else {
	        $eventId = $_GET['eventId'];
	    }
	    $data['owner_info'] = user_helper::getUserinfoByUserName($_SESSION['username']);
	    $data['username']			= $_SESSION['username'];
	    $data['eventId']			= $eventId;
	    $data['event_type_list']	= $this->Events->getEventType();
	    $data['event_pri_list']		= $this->Events->getEventPriority();
	    $data['event_emergency_list']		= $this->Events->getEventEmergency();
	    $data['event_influencearea_list'] = $this->Events->getEventInfluencearea();
	    $data['event_status_list'] = $this->Events->getEventStatus();
	    $data['event_source_list'] = $this->Events->getEventSource();
	    $data['event_usertype_list']= $this->options->getOptionsByType('event_usertype');
	    $data['event_cat_list']		= $this->options->getOptionsByType('event_category');
		$data['event_subclass']		= $this->options->getOptionsByType('event_subclass', 10);
		$data['group_list']		= $this->groups->getAllGroups();
		$data['charger_list']		= $this->workers->getAllWorkersByGroupId(1);
	    $this->load->view('innerUser/NewRequestByAgent', $data);
	}

    function AddEventByAgent()
	{
	    $params = array_merge($_GET, $_POST);
	    if (!isset($params['eventId']) || !$params['eventId']) {
	        redirect('/innerUser/NewRequestByAgent', 'refresh');
	    }
	    $eventId = intval($params['eventId']);
	    $row = array(
	        'event_owner'			=> trim($params['event_owner']),
	        'event_usertype'		=> $params['event_usertype'],
	        'event_type'			=> $params['event_type'],
	        'event_emergency'		=> $params['event_emergency'],
    	    'event_influencearea'	=> $params['event_influencearea'],
	        'event_begintime'	    => $params['event_begintime'],
	    	'event_source'		    => $params['event_source'],
    	    'event_category'		=> $params['event_category'],
    	    'event_subclass'		=> $params['event_subclass'],
    	    'event_title'			=> trim($params['event_title']),
    	    'event_desc'			=> trim($params['event_desc']),
			'event_influencebusiness'	=> trim($params['event_influencebusiness']),
			'event_status'			=> events_config::$event_status['EVENT_STATUS_CREATE'],
			'event_isstaff'			=> Events::USER_STAFF_INNER,
			'event_addtime'			=> date('Y-m-d H:i:s')
	    );
	    if(!$this->Events->modifyEventById($eventId, $row)){
	        echo $this->Events->getErrNo . "||" . $this->Events->getErrMessage();
	        exit;
	        redirect('/innerUser/NewRequestByAgent/?eventId/'.$eventId, 'refresh');
	    }
//	    if ($row['event_charger']) {
//	        $rId = $this->Events->addWorkRecord($eventId, $row['event_charger'], trim($params['operate_content']));
//	    	if (!$rId) {
//	    		echo $this->Events->getErrNo . "||" . $this->Events->getErrMessage();
//	            exit;
//	    	}
//	    }

//	    die("添加成功,event_id: {$eventId}\nparams:".print_r($row));
		//发邮件给创建者
	    $event = $this->Events->getEventById($eventId);
	    $this->load->helper("mail_helper");
	    mail_helper::newEventTOCustomerMail($this, $event);
	    redirect("/innerUser/ViewRequestByAgent?eventId=$eventId", 'refresh');
	}

   public function getGroupCharger()
	{
		$params = array_merge($_GET, $_POST);
	    $this->load->model('workers');
	    $groupId		= intval($params['group_id']);
		$rows			= $this->workers->getAllWorkersByGroupId($groupId);
		die(json_encode($rows));
	}

	public function AgentRequestList()
	{
		$params = array_merge($_GET, $_POST);
	    $data['requestGroup'] = isset($params['r']) ? $params['r'] : 1	 ;

		$this->load->view('innerUser/AgentRequestList', $data);
	}

	public function AgentRequestData()
	{
		$owner = $_SESSION['username'];
		$listDisplayType = array(1=>1,2=>2);
	    $params = array_merge($_GET, $_POST);
		$page = !isset($params['page']) ? 1 : intval($params['page']);
		$r = !isset($params['r'])||!isset($listDisplayType[$params['r']]) ? 2 : intval($params['r']);
		$rows = !isset($params['rows']) ? 10 : intval($params['rows']);
		$sidx = !isset($params['sidx']) || !$params['sidx'] ? 'event_id' : $params['sidx'];
		$sord = !isset($params['sord']) || !$params['sord'] ? 'DESC' : $params['sord'];
		$offset = ($page-1)*$rows;
		$where = array('event_owner'=>$owner, 'event_isstaff'=>Events::USER_STAFF_INNER);
		if ($r!=1) {
//			$where['event_status'] = array(Events::EVENT_STATUS_CREATE, Events::EVENT_STATUS_PROCESSING);
			$where['event_status']	= array(
				events_config::$event_status['EVENT_STATUS_CREATE'],
				events_config::$event_status['EVENT_STATUS_PROCESSING']
			);
		} else {
			$where['event_status']	= events_config::$event_status;
		}
		$count = $this->Events->getEventCount($where);

		$data = array();
        if ($count) {
        	$data = $this->Events->getEventList($where, $offset, $rows, $sidx, $sord);
        	$this->_parseEvents($data);
        }
		$arr = array();
		$arr['total'] = ceil($count/$rows);
		$arr['records'] = $count;
		$arr['page'] = $page;
		$arr['rows'] = $data;
		echo json_encode($arr);
	}

	function ViewRequestByAgent()
	{
	    $params = array_merge($_GET, $_POST);
		$this->load->model('options');
		$this->load->model('groups');
		if (!isset($params['eventId']) || !$params['eventId']) {
			die("您要查看的事件不存在");
		}
		$eventId	= intval($params['eventId']);

	    $row		= $this->Events->getEventById($eventId);
	    if (!$row) {
			die("您要查看的事件不存在");
	    }
		if ($row['event_owner'] != $_SESSION['username'])
			die("您要查看的事件不存在");
	    $userInfo = array();
	    $data['owner_info'] = user_helper::getUserinfoByUserName($row['event_owner']);
	    $data['event']		= $row;
	    $data['eventId']	= $eventId;
	    $data['event_type_list']	= $this->Events->getEventType();
	    $data['event_pri_list']		= $this->Events->getEventPriority();
	    $data['event_emergency_list']		= $this->Events->getEventEmergency();
	    $data['event_influencearea_list'] = $this->Events->getEventInfluencearea();
	    $data['event_status_list'] = $this->Events->getEventStatus();
	    $data['event_source_list'] = $this->Events->getEventSource();
	    $data['event_usertype_list']= $this->options->getOptionsByType('event_usertype');
	    $data['event_cat_list']		= $this->options->getOptionsByType('event_category');
		$data['event_subclass']		= $this->options->getOptionsByType('event_subclass', $row['event_category']);
		$data['group_list']		= $this->groups->getAllGroups();
		$groupId = $row['event_groupid'] ? $row['event_groupid'] : 4;
		$data['charger_list']		= $this->workers->getAllWorkersByGroupId($groupId);
		//工作纪录查询
		$this->load->model("workrecords");
		$data['event_records']		= $this->workrecords->getRecordsById($eventId);
		//附件查询
		$this->load->model("attachments");
		$data['event_attachments']	= $this->attachments->getAttachments(array(
			'event_id'=>$eventId,
			'attachment_isreply'=>Events::ATTACHMENT_NOTREPLY
		));
		$this->load->view('innerUser/ViewRequestByAgent', $data);
	}

	private function _parseEvents(&$events)
	{
	    if (!$events) {
	    	return ;
	    }
	    $this->load->helper("options_helper");
	    $priorityList = $this->Events->getEventEmergency();
	    $typeList = options_helper::returnOptionsByCode($this->Events->getEventType(), true);
	    $statusList = options_helper::returnOptionsByCode($this->Events->getEventStatus(), true);
	    foreach($events as $k=>$row) {
	        $row['event_emergency_name'] = !isset($priorityList[$row['event_emergency']]) ? "未定义":$priorityList[$row['event_emergency']];
	        $row['event_type'] = !isset($typeList[$row['event_type']]) ? "未定义":$typeList[$row['event_type']];

	        $row['event_desc_sub'] = mb_strlen($row['event_desc'])>60 ? mb_substr($row['event_desc'], 0, 60) : $row['event_desc'];
	        $row['event_status_name'] = !isset($statusList[$row['event_status']]) ? "未定义":$statusList[$row['event_status']];
			$row['event_title']	= htmlspecialchars($row['event_title']);
	        $addTime = strtotime($row['event_addtime']);
	        $updateTime = strtotime($row['event_updatetime']);
	        $today = strtotime(date("Y-m-d"));
	        $row['level'] = 1;
	        if($row['event_status']==25) {
    	        if (($_SERVER['REQUEST_TIME']-$addTime)>=5*86400) {
    	        	$row['level'] = 3;
    	        } elseif(($_SERVER['REQUEST_TIME']-$addTime)>=86400) {
    	            $row['level'] = 2;
    	        }
	        }
			if ($addTime<$today) {
				$row['event_addtime'] = date("Y-m-d", $addTime);
			} else {
				$row['event_addtime'] = date("H:i:s", $addTime);
			}
	    	if ($updateTime<$today) {
				$row['event_updatetime'] = date("Y-m-d", $updateTime);
			} else {
				$row['event_updatetime'] = date("H:i:s", $updateTime);
			}
	        $events[$k] = $row;
	    }
	}

	public function openagain()
	{
		$eventId	= $this->getpara("eventId");
		$eventId	= intval($eventId);
		if (empty($eventId) || $eventId<0)
			die(json_encode(array('success' => false, 'msg'	=> '不存在的事件ID:'.$eventId)));
		$row		= $this->Events->getEventById($eventId);
		if ($row['event_owner'] != $_SESSION['username'])
			die(json_encode(array('success' => false, 'msg' => '不存在此事件ID:'.$eventId)));
		if ($row['event_status'] != events_config::$event_status['EVENT_STATUS_SOLUTION'])
			die(json_encode(array('success' => false, 'msg' => '事件没有解决，因此不用重新打开')));
		$arr['event_status']	= events_config::$event_status['EVENT_STATUS_CREATE'];
		$arr['event_charger']	= '';
		$arr['event_groupid']	= 0;
		$arr['event_solvetime']	= '';
		$username 				= $_SESSION['username'];

		if ($this->Events->modifyEventById($eventId, $arr))
		{
			$this->Events->addWorkRecord($eventId, $username, " 重新打开了此事件");
			die(json_encode(array("success"=>true, "msg"=>"事件重新打开，您可以追加相应描述")));
		} else {
			die(json_encode(array("success"=>false, "msg"=>"事件重新打开失败，请稍后再试")));
		}
	}

	/**
	 * 追加描述
	 */
	function appendDesc()
	{
		$desc 			= trim($this->getpara('appendDesc'));
		if(!$desc)
			die(json_encode(array('status'=>false,'msg'=>'描述不能为空')));
		if(mb_strlen($desc,'utf-8')>500)
			die(json_encode(array('status'=>false,'msg'=>'描述超过500字符')));
		$compartLine	= "\r---------------".date('Y-m-d H:i:s')."追加---------------\r";
		$eventId		= intval($this->getpara('eventId'));
		$username 		= $_SESSION['username'];
	    if (!$eventId || !$desc) {
	        redirect('incident/NewRequestByCustomer', 'refresh');
	    }
	    $row			= $this->Events->getEventById($eventId);
		if ($row['event_owner']!=$_SESSION['username']) {
			die(json_encode(array('status'=> false, 'msg' => '查询不到此事件ID')));
	    }
	    if ($row['event_status'] == events_config::$event_status['EVENT_STATUS_SOLUTION'] || $row['event_status'] == events_config::$event_status['EVENT_STATUS_CLOSE'])
	    	die(json_encode(array('status' => false, 'msg' => '事件解决中或已经关闭，不能追加描述')));
	    $event_desc = $compartLine.$desc;
	    $this->load->model('Events');
	    $row		= array(
    	    'event_desc'			=> $event_desc
	    );

	    if(!$this->Events->appendDescById($eventId, $row)){
	        echo $this->Events->getErrNo . "||" . $this->Events->getErrMessage();
	        exit;
	        redirect('incident/ViewRequestByCustomer/eventId/'.$eventId, 'refresh');
	    }
	    $this->Events->addWorkRecord($eventId, $username, " 追加了描述：\n".$desc);
		echo json_encode(array('status'=>true, 'msg'=>$event_desc));
	}

	public function eventDetail()
	{
		$eventId	= $this->getpara("event_id");
		if (empty($eventId) || $eventId<0)
			die(json_encode(array('success' => false, 'msg'	=> '不存在的事件ID:'.$eventId)));
		$row		= $this->Events->getEventById($eventId);
		if ($row['event_owner']!=$_SESSION['username']) {
			die(json_encode(array('success' => false, 'msg' => '查询不到此事件ID')));
	    }
		if (!empty($row)) {
			$row['success']	= true;
			die(json_encode($row));
		} else {
			die(json_encode(array('success' => false, 'msg' => '查询不到此事件ID')));
		}
	}
	function loadCloseForm()
	{
		$eventId	= $this->getpara("id");
		if (empty($eventId))
			die("不存在的事件ID");
		$row		= $this->Events->getEventById($eventId);
		$row['event_status']	= @events_config::$event_status_name[$row['event_status']];
		$this->load->view('innerUser/CloseForm', $row);
	}

	public function close_event()
	{
		$eventId		= $this->getpara("event_id");
		$closereason	= $this->getpara("event_closereason");
		if (empty($eventId))
			die(json_encode(array('success' => flase, 'msg'=>'不存在的事件ID')));
		$row		= $this->Events->getEventById($eventId);
	    if (!$row || $row['event_owner']!=$_SESSION['username']) {
	    	die(json_encode(array('success' => flase, 'msg'=>'不存在的事件ID')));
	    }

		$row		= array(
			'event_status'		=> events_config::$event_status['EVENT_STATUS_CLOSE'],
			'event_closereason'	=> $closereason
		);
		if ($this->Events->modifyEventById($eventId, $row)){
			//事件关闭发邮件给创建者
		    $event = $this->Events->getEventById($eventId);
		    $this->load->helper("mail_helper");
		    mail_helper::closeEventTOCustomerMail($this, $event);
			die(json_encode(array('success' => true, 'msg'=>'事件已关闭')));
		}
		else {
			die(json_encode(array('success' => flase, 'msg'=>'提交失败，请稍后再试')));
		}
	}


}
